from django.test import TestCase
from django.contrib.auth import get_user_model
from .models import Role, Permission, Menu

User = get_user_model()


class RBACModelTests(TestCase):
    """RBAC模型测试"""

    def setUp(self):
        """测试数据准备"""
        self.user = User.objects.create_user(
            username='testuser',
            email='test@example.com',
            password='testpass123'
        )

        self.permission = Permission.objects.create(
            name='测试权限',
            code='test_permission',
            description='测试权限描述'
        )

        self.role = Role.objects.create(
            name='测试角色',
            code='test_role',
            description='测试角色描述'
        )
        self.role.permissions.add(self.permission)

    def test_user_role_assignment(self):
        """测试用户角色分配"""
        self.user.roles.add(self.role)
        self.assertIn(self.role, self.user.roles.all())

    def test_role_permissions(self):
        """测试角色权限"""
        self.assertIn(self.permission, self.role.permissions.all())

    def test_user_permissions_through_role(self):
        """测试用户通过角色获取权限"""
        self.user.roles.add(self.role)
        user_permissions = Permission.objects.filter(role__users=self.user)
        self.assertIn(self.permission, user_permissions)
